package com.lc;

import com.lc.action.MyServlet;
import com.lc.adapter.HttpAdapter;
import com.lc.config.Configuration;
import com.lc.mapper.Context;
import com.lc.mapper.Host;
import com.lc.mapper.Wrapper;
import com.lc.parser.ServerXmlParser;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import javax.net.ssl.HostnameVerifier;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.List;

/**
 * @author liuc
 * @date 2021/5/5
 * @description 启动类
 **/
public class Bootstrap {

    private Master master ;
    private Configuration configuration;

    public void start() throws IOException {

        //1.加载xml
        load();
        //2.开启服务
        doStart();
    }

    public void load(){
        //加载不同的包(webapps)下面的文件
        this.configuration = new Configuration();
        //添加初始化的的root
        setDefaultHost(configuration);
        //解析外部部署的
        localServerXml();
    }

    private void localServerXml() {
        ServerXmlParser xmlParser = new ServerXmlParser(configuration,this.getClass().getClassLoader().getResourceAsStream("server.xml"));
        xmlParser.parse();
    }


    public void setDefaultHost(Configuration configuration){
        String root = "localhost";
        Wrapper wrapper = new Wrapper("/",new MyServlet());
        Context context = new Context("/");
        context.addWrapper(wrapper);
        context.setDir(this.getClass().getClassLoader().getResource("").getPath());
        Host host = new Host(root);
        host.addContext(context);
        HttpAdapter adapter = new HttpAdapter(configuration, root);
        adapter.setHost(host);
        configuration.addAdapter(adapter, root);
    }

    /**
     * 开启一个服务
     * @throws IOException
     */
    public void doStart() throws IOException {
        master = new Master(configuration);
        master.start();
    }


    public void stop(){
        //todo 给线程发送一个打断的信号
    }


    public static void main(String[] args) throws IOException, InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.start();
        Thread.currentThread().join();
    }
}
